import React,{useState,useEffect,Fragment, useRef} from "react"
import {debounce} from "@/utils/tool"
import NullData from "@/components/nullData/NullData"
import BrankList from "./BrankList"
import SubNav from "./SubNav"
import "./brank.scss"
import {query ,  getBoundingClientRect ,Linear,onFn} from "@/utils/elUtils.js"
import PropTypes from "prop-types"
import CommService from "@/data/index"
function BrandIndex(props){
    function getInitData(){
        const localBrand=JSON.parse(sessionStorage.localBrand||'[]');
        return  localBrand.reduce((item,children)=>{
            let index=item.findIndex(sub=>sub.first_letter==children.first_letter);
            if(index==-1){
                item.push({
                    first_letter: children.first_letter,
                    children:[{
                        ...children
                    }]
                })
            }else{
                item[index].children.push({...children})
            }
            return  item
        },[])
    }
   
    const {headerEl}=props,
          queryRef=useRef(),
          [list,setList]=useState(getInitData()),
          [scrollFlg,setScrollFlg]=useState(false),
          [searchValue,setSearchValue]=useState(''),
          [checkItem,setCheckItem]=useState(null);
    useEffect(()=>{
        if(checkItem){
            const {top}=getBoundingClientRect(query(`#${checkItem}`)),
                  {height}=getBoundingClientRect(headerEl.current),
                  queryHeight=getBoundingClientRect(queryRef.current).height,
                  scrollTop=document.documentElement.scrollTop||document.body.scrollTop,
                  scrollEnd=top+scrollTop-height-queryHeight;
            let startTime=0,
                endTime=Math.ceil(Math.abs((scrollEnd==0?scrollTop+height+queryHeight:scrollEnd)/50));
                setScrollFlg(true);
            (function scrollFn(){
                startTime++;
                if(startTime<=endTime){
                    window.scrollTo(0, Linear(startTime, scrollTop,scrollEnd, endTime))
                    requestAnimationFrame(scrollFn)
                }else{
                    setScrollFlg(false)
                }
            })()
        }
        
    },[checkItem])
    const inputFn=debounce(function(event){
        let value=(event.target.value||'').trim();
        if(value!=searchValue){
            let list=getInitData().reduce((a,item)=>{
                let children=item.children.filter(subItem=>subItem.brand_name.includes(value));
                if(children&&children.length){
                    a.push({
                        first_letter: item.first_letter,
                        children
                    })
                }
                return a;
            },[])
            setSearchValue(value)
            setList(list)
            setScrollFlg('');
        }
    })
    if(list&&!list.length){
        CommService["serviceBrand"]().then(res=>{
            sessionStorage.localBrand=JSON.stringify(res.result)
            setList(getInitData())
        })
    }
    return (
        <>
            <div className="brank-list">
                <div className="brand_nav" ref={queryRef}>
                    <header className="box-size">
                        <div className="search flex">
                            <label className="icon-chaxun iconfont query_icon"></label>
                            <div className="flex-1">
                                <input type="text" onInput={(e)=>inputFn(e)} className="inp" placeholder="请输入查询条件" />
                            </div>
                        </div>
                    </header>
                </div>
                {
                list.length?list.map(item=>{
                        return(<Fragment key={item.first_letter}>
                            <div className="tit" id={item.first_letter}>{item.first_letter}</div>
                            <BrankList list={item.children} />
                        </Fragment>)
                    }):(<NullData></NullData>)
                }
            </div>
            {
               list.length? <SubNav checked={checkItem} scrollFlg={scrollFlg}  setChecked={setCheckItem} list={list}/>:''
            }
        </>
    )
}
BrandIndex.defaultProps={
    headerEl:""
}
BrandIndex.propTypes={
    headerEl:PropTypes.oneOfType([ PropTypes.object,PropTypes.string,PropTypes.element])
}
export default BrandIndex